import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const Login = () => import('../components/Login/Login')
const Home = () => import('../components/Home/Home')
const User = () => import('../components/Main/User')
const Welcome = () => import('../components/Main/Welcome')
const Rights = () => import('../components/Main/power/Rights')
const Roles = () => import('../components/Main/power/Roles')
const Cate = () => import('../components/Main/goods/Cate')
const Params = () => import('../components/Main/goods/Params')
const List = () => import('../components/Main/goods/List')
const Add = () => import('../components/Main/goods/Add')
const Order = () => import('../components/Main/order/Order')
const Report = () => import('../components/Main/report/Report')


const routes = [
  {
    path: '',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {path: '/welcome', component: Welcome},
      {path: '/users', component: User},
      {path: '/rights', component: Rights},
      {path: '/roles', component: Roles},
      {path: '/categories', component: Cate},
      {path: '/params', component: Params},
      {path: '/goods', component: List},
      {path: '/goods/add', component: Add},
      { path: '/orders', component: Order},
      { path: '/reports', component: Report},
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 定义路由导航守卫
router.beforeEach((to, from, next) => {
  // 如果刚进来访问的是 login 则直接返回放行
  if(to.path == '/login') return next();
  // 获取 缓存中的 token 值判断是否存在
  const tokenStr = window.sessionStorage.getItem('token')
  if(!tokenStr) return next('/login')
  next()
})


export default router
